package com.derive.education_service.web.platform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.derive.education_service.common.global.Paper;
import com.derive.education_service.common.global.ResponseMessage;
import com.derive.education_service.entity.Platform;
import com.derive.education_service.entity.PlatformResources;
import com.derive.education_service.mapper.PlatformMapper;
import com.derive.education_service.mapper.PlatformResourcesMapper;
import com.derive.education_service.utils.MyFileUtils;
import com.derive.education_service.web.platform.bean.dto.PlatformAdd;
import com.derive.education_service.web.platform.bean.dto.PlatformResAdd;
import com.derive.education_service.web.platform.bean.dto.PlatformUp;
import com.derive.education_service.web.platform.bean.dto.QueryParam;
import com.derive.education_service.web.platform.service.PlatformService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 机构实现接口
 */
@Service
@Component
@Slf4j
public class PlatformServiceImpl implements PlatformService {

    @Autowired
    private PlatformMapper platformMapper;

    @Autowired
    private PlatformResourcesMapper platformResourcesMapper;

    @Autowired
    private MyFileUtils myFileUtils;

    /**
     * 先新增机构，新增成功才能上传机构资源(流程化)
     * 新增机构 -- 机构信息
     *
     * @return
     */
    @Override
    public ResponseMessage addPlatform(MultipartFile file, PlatformAdd platformAdd) {
        // 数据填充
        Platform platform = new Platform();
        BeanUtils.copyProperties(platformAdd, platform);
        // 文件上传
        try {
            ResponseMessage r = myFileUtils.uploadFile(file, "platformLogo");
            if (r.getStatus() == 0) {
                // 成功
                platform.setPlatformLogo(String.valueOf(r.getData()));
            } else {
                // 失败
                log.error("新增机构文件上传文件异常{[addPlatform-58]}：" + r.getMsg());
                return r;
            }
        } catch (IOException e) {
            // 失败
            log.error("新增机构文件上传文件异常{[addPlatform-63]}：");
            e.printStackTrace();
            return ResponseMessage.createByErrorMessage("新增机构文件上传文件异常{[addPlatform-65]}");
        }
        platform.setCreateTime(new Date());
        platform.setUpdateTime(new Date());
        // 插入数据
        int row = platformMapper.insert(platform);
        if (row <= 0) {
            return ResponseMessage.createByErrorMessage("数据异常");
        } else {
            return ResponseMessage.createBySuccessMessage("成功");
        }
    }

    /**
     * 先新增机构，新增成功才能上传机构资源(流程化)
     * 新增机构资源 -- 带机构id
     *
     * @return
     */
    @Override
    public ResponseMessage addPlatformRes(List<MultipartFile> files, PlatformResAdd platformResAdd) {
        // 数据填充
        PlatformResources platformResources = new PlatformResources();
        BeanUtils.copyProperties(platformResAdd, platformResources);
        // 机构信息
        Platform platform = platformMapper.selectById(platformResources.getPlatformId());
        int row = 0;
        // 文件上传
        try {
            for (MultipartFile f : files) {
                ResponseMessage r = myFileUtils.uploadFile(f, "platformRes" + File.separator + platform.getPlatformName());
                if (r.getStatus() == 0) {
                    // 成功
                    platformResources.setResourcesUrl(String.valueOf(r.getData()));
                    platformResources.setCreateTime(new Date());
                    platformResources.setUpdateTime(new Date());
                    // 插入数据
                    row = platformResourcesMapper.insert(platformResources);
                } else {
                    // 失败
                    log.error("新增机构资源文件上传文件异常{[addPlatformRes-103]}：" + r.getMsg());
                    return r;
                }
            }
            if (row <= 0) {
                return ResponseMessage.createByErrorMessage("数据异常");
            } else {
                return ResponseMessage.createBySuccessMessage("成功");
            }
        } catch (IOException e) {
            // 失败
            log.error("新增机构文件资源上传文件异常{[addPlatform-63]}：");
            e.printStackTrace();
            return ResponseMessage.createByErrorMessage("新增机构资源文件上传文件异常{[addPlatform-65]}");
        }
    }

    /**
     * 删除机构 -- 机构信息+机构资源信息+(内容关联信息)
     *
     * @return
     */
    @Override
    public ResponseMessage delPlatform(Integer platformId) {
        // 查询需要删除的机构logo信息
        Platform platform = platformMapper.selectById(platformId);
        String logo = platform.getPlatformLogo();
        // 查询需要删除的机构资源信息
        QueryWrapper<PlatformResources> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("platform_id", platformId);
        List<PlatformResources> platformResourcesList = platformResourcesMapper.selectList(queryWrapper);
        // 删除logo资源
        ResponseMessage dr = myFileUtils.delFile(logo);
        if (dr.getStatus() == 1) {
            // 失败退出
            return dr;
        }
        // 删除关联资源
        for (PlatformResources p : platformResourcesList) {
            ResponseMessage drs = myFileUtils.delFile(p.getResourcesUrl());
            if (dr.getStatus() == 1) {
                // 失败退出
                return drs;
            }
        }
        // 删除机构信息
        int row = platformMapper.deleteById(platformId);
        if (row <= 0) {
            return ResponseMessage.createByErrorMessage("删除" + platform + "异常");
        } else {
            return ResponseMessage.createBySuccessMessage("删除" + platform + "成功");
        }
    }

    /**
     * 删除机构资源数据 -- 资源id
     *
     * @param prId
     * @return
     */
    @Override
    public ResponseMessage delPlatformResByPrId(Integer prId) {
        // 删除资源
        String url = platformResourcesMapper.selectById(prId).getResourcesUrl();
        ResponseMessage dr = myFileUtils.delFile(url);
        if (dr.getStatus() == 1) {
            // 失败退出
            return dr;
        }
        // 删除信息
        int row = platformResourcesMapper.deleteById(prId);
        if (row <= 0) {
            return ResponseMessage.createByErrorMessage("异常");
        } else {
            return ResponseMessage.createBySuccessMessage("删除成功");
        }
    }

    /**
     * 查询服务平台所有机构 -- 分页参数 -- 按条件
     *
     * @return
     */
    @Override
    public Paper<Platform> getPlatformList(QueryParam queryParam) {
        // 封装分页
        Page<Platform> page = new Page<>();
        page.setCurrent(queryParam.getCurrent());
        page.setSize(queryParam.getSize());

        QueryWrapper<Platform> queryWrapper = new QueryWrapper<>();
        if (queryParam.getPlatformName() != null && !queryParam.getPlatformName().isEmpty()) {
            queryWrapper.like("platform_name", queryParam.getPlatformName());
        }

        Page<Platform> platformPage = platformMapper.selectPage(page, queryWrapper);

        // 数据封装返回
        Paper<Platform> platformPaper = new Paper<>();
        platformPaper.setCurrent(platformPage.getCurrent());
        platformPaper.setSize(platformPage.getSize());
        platformPaper.setPages(platformPage.getPages());
        platformPaper.setTotal(platformPage.getTotal());
        platformPaper.setData(platformPage.getRecords());
        return platformPaper;
    }

    /**
     * 根据id查询机构详细信息
     *
     * @param platformId
     */
    @Override
    public ResponseMessage getPlatformInfoById(Integer platformId) {
        // 查询机构信息
        Platform platform = platformMapper.selectById(platformId);
        // 查询机构资源信息
        QueryWrapper<PlatformResources> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("platform_id", platformId);
        List<PlatformResources> platformResources = platformResourcesMapper.selectList(queryWrapper);
        HashMap map = new HashMap();
        map.put("platform", platform);
        map.put("platformResources", platformResources);

        if (platform == null) {
            return ResponseMessage.createByErrorMessage("机构不存在{[getPlatformInfoById-238]}");
        } else {
            return ResponseMessage.createBySuccess(map);
        }
    }

    /**
     * 编辑机构信息
     */
    @Override
    public ResponseMessage upPlatformById(MultipartFile file, PlatformUp platformUp) {
        Platform platform = new Platform();
        BeanUtils.copyProperties(platformUp, platform);
        // 判断是否更新文件
        if (file != null && !file.isEmpty()) {
            // 更新了文件 -- 先删除原来的文件
            String logo = platformMapper.selectById(platformUp.getPlatformId()).getPlatformLogo();
            // 删除原来的文件
            ResponseMessage dr = myFileUtils.delFile(logo);
            if (dr.getStatus() == 1) {
                // 失败退出
                return dr;
            }
            // 文件上传
            try {
                ResponseMessage r = myFileUtils.uploadFile(file, "platformLogo");
                if (r.getStatus() == 0) {
                    // 成功 -- 设置新的icon地址
                    platform.setPlatformLogo(String.valueOf(r.getData()));
                } else {
                    // 失败
                    log.error("编辑机构文件上传文件异常{[upPlatformById-161]}：" + r.getMsg());
                    return r;
                }
            } catch (IOException e) {
                log.error("编辑机构文件上传文件异常{[upPlatformById-165]}");
                e.printStackTrace();
                return ResponseMessage.createByErrorMessage("机构文件上传异常");
            }
        }
        platform.setUpdateTime(new Date());
        // 更新数据
        int row = platformMapper.updateById(platform);
        if (row <= 0) {
            return ResponseMessage.createByErrorMessage("异常");
        } else {
            return ResponseMessage.createBySuccessMessage("成功");
        }
    }
}
